<script setup lang="ts">
import { reactive, watch, onMounted } from 'vue'
import { useCurrentInstance } from '@/common/utils/methods';
import { ResponseType } from '@/common/types/response';
import { ParamsType } from '@/common/types/conf'

const { $axios, $loading, branchId, brandId } = useCurrentInstance();

const props = defineProps<{
  url: string         // 列表接口地址
  params: ParamsType  // 列表接口请求参数
  list: object[]      // 列表数据
  getData: boolean    // 获取数据标记
  autoLoad?: boolean   // 自动加载
  listKeyName?: string // 返回列表数据对应的key值
}>()

const emit = defineEmits<{
  (e: 'setTotalNum', num: number): void      // 更新列表总条数
  (e: 'update:list', list: object[]): void   // 更新列表list
  (e: 'update:getData', flag: boolean): void // 更新列表同步数据标记
}>()

const data = reactive({
  pageSize: 10,
  pageNo: 1,
  totalRowCount: 0
})

const sizeChange = (pageSize: number) => {
  data.pageSize = pageSize;
  data.pageNo = 1;
  getList();
}
const currentChange = (pageNo: number) => {
  data.pageNo = pageNo;
  getList();
}

const getList = () => {
  let params = {
    ...props.params,
    pageSize: data.pageSize,
    pageNo: data.pageNo,
    branchId,
    brandId
  };
  for (let key in params) {
    if (!params[key] && params[key] !== 0) {
      delete params[key]
    }
  }
  const loadingInstance = $loading({
    fullscreen: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.6)'
  })
  $axios.post(props.url, params).then((res: ResponseType) => {
    const { code, data: { totalRowCount } } = res;
    if (code === '200') {
      // 列表数据默认在 list下，可以自定义keyName
      const listKeyName = props.listKeyName || 'list';
      const list = res.data[listKeyName]

      // 如果未返回列表数据总条数，则总数默认等于当前返回数据总条数
      data.totalRowCount = totalRowCount ? Number(totalRowCount) : list.length;

      emit('update:list', list);
      emit('setTotalNum', data.totalRowCount)
    } else {
      emit('update:list', []);
    }
    loadingInstance.close();
  }).catch(() => {
    emit('update:list', []);
    loadingInstance.close();
  })

  // 获取数据重置获取数据标记
  emit('update:getData', false);
}

watch(() => props.getData, (val) => {
  if (val) getList();
})

onMounted(() => {
  // 首次加载自动加载列表数据
  if (props.autoLoad) {
    getList();
  }
})
</script>

<template>
  <div class="container">
    <el-pagination
      @size-change="sizeChange"
      @current-change="currentChange"
      :current-page="data.pageNo"
      :page-sizes="[10, 20, 30, 50, 100]"
      :page-size="data.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="data.totalRowCount"
    ></el-pagination>
  </div>
</template>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>